<template>
  <div>
    <!-- label -->
    <label v-if="label">{{ label }}</label>

    <slot></slot>

    <!-- 校验信息显示 -->
    <p v-if="error">{{ error }}</p>
  </div>
</template>

<script>
// Asyc-validator
import Schema from 'async-validator'
import emitter from '@/mixins/emitter'
export default {
  name: 'KFormItem',
  componentName: 'KFormItem',
  mixins: [emitter],
  inject: ['form'],
  data() {
    return {
      error: '', // error是空说明校验通过
    }
  },
  props: {
    label: {
      type: String,
      default: '',
    },
    prop: {
      type: String,
    },
  },
  mounted() {
    this.$on('validate', () => {
      this.validate()
    })
    // 派发事件通知KForm，新增一个KFormItem实例,参数就是自己哈哈哈
    // 自己做有无prop的判断
    if (this.prop) {
      this.dispatch('KForm', 'kkb.form.addField', [this])
    }
  },
  methods: {
    validate() {
      // 规则
      const rules = this.form.rules[this.prop]
      // 当前值
      const value = this.form.model[this.prop]

      // 校验描述对象
      const desc = { [this.prop]: rules }
      // 创建Schema实例
      const schema = new Schema(desc)
      return schema.validate({ [this.prop]: value }, (errors) => {
        if (errors) {
          this.error = errors[0].message
        } else {
          // 校验通过
          this.error = ''
        }
      })
    },
  },
}
</script>

<style scoped></style>
